package com.xiangban.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiangban.model.dto.TSystemDto;
import com.xiangban.service.MessageService;
import com.xiangban.utils.HttpClientUtil;
import com.xiangban.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author ly
 * @date 2021/11/22 12:07
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    RedisUtil redisUtil;

    private  static  String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    @Override
    public Object sendByOpenId(TSystemDto tSystemDto) {//accessToken, 模板id open id  参数
        String yanglaodajie_access_token = redisUtil.get("yanglaodajie_access_token");
        //循环openid 发送
        String AccessTokenURL = url.replace("ACCESS_TOKEN", yanglaodajie_access_token);
        HashMap<String, Object> MessageMap = new HashMap<>();
        HashMap<String,Object> dataMap = new HashMap<>();
        HashMap<String,String> firstMap = new HashMap<>();
        HashMap<String,String> keyword1 = new HashMap<>();//申请人
        HashMap<String,String> keyword2 = new HashMap<>();//时间
        HashMap<String,String> remark = new HashMap<>();// 备注
        HashMap<String,String> miniprogram = new HashMap<>();
        miniprogram.put("appid","wxc1e0e684cc5687c8");
        miniprogram.put("pagepath","pages/index/index");
        //请假模板
        firstMap.put("value","您有一条请假待审批");
        firstMap.put("color","#173177");
        keyword1.put("value",tSystemDto.getKey2()); //申请人
        keyword1.put("color","#173177");
        keyword2.put("value",tSystemDto.getKey3());//时间
        keyword2.put("color","#173177");
        remark.put("value",tSystemDto.getKey4());//备注
        remark.put("color","#173177");
        dataMap.put("first",firstMap);//开头
        dataMap.put("keyword1",keyword1);//申请人
        dataMap.put("keyword2",keyword2);//时间
        dataMap.put("remark",remark);//备注
        MessageMap.put("template_id",tSystemDto.getTemplateId());
        MessageMap.put("url","https://www.baidu.com/");
        MessageMap.put("topcolor","#FF0000");
        MessageMap.put("data",dataMap);
        MessageMap.put("miniprogram",miniprogram);

        for (String openid : tSystemDto.getOpenId()) {
           MessageMap.put("touser",openid);
            String s1 = JSON.toJSONString(MessageMap);
            String s = HttpClientUtil.doPostJson(AccessTokenURL, JSON.toJSONString(MessageMap));
             Map<String, Object> parse = (Map<String, Object>) JSON.parse(s);
            if (parse.get("errmsg").toString().equals("ok")){
                return true;
            }else {
                return false;
            }
        }
        return null;
    }
}
